package com.example.himalaya2;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.viewpager.widget.ViewPager;


import android.content.Intent;
import android.media.Image;
import android.os.Bundle;

;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.himalaya2.adapters.IndicaorAdapter;
import com.example.himalaya2.adapters.MainContentAdapter;
import com.example.himalaya2.interfaces.IPlayerCallback;
import com.example.himalaya2.presenters.PlayerPresenter;
import com.example.himalaya2.presenters.RecommendPresenter;
import com.example.himalaya2.utils.LogUtil;
import com.example.himalaya2.views.RoundRectImageView;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.squareup.picasso.Picasso;
import com.ximalaya.ting.android.opensdk.datatrasfer.CommonRequest;
import com.ximalaya.ting.android.opensdk.datatrasfer.IDataCallBack;
import com.ximalaya.ting.android.opensdk.model.album.Album;
import com.ximalaya.ting.android.opensdk.model.category.Category;
import com.ximalaya.ting.android.opensdk.model.category.CategoryList;
import com.ximalaya.ting.android.opensdk.model.track.Track;
import com.ximalaya.ting.android.opensdk.player.service.XmPlayListControl;

import net.lucode.hackware.magicindicator.MagicIndicator;
import net.lucode.hackware.magicindicator.ViewPagerHelper;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MainActivity extends AppCompatActivity implements IPlayerCallback {  // AppCompatActivity 继承自FragmentActivity

    private static final String TAG = "MainActivity";

    private MagicIndicator mMagicIndicator;   // FrameLayout

    private ViewPager mContentPage;  // ViewGroup

    private IndicaorAdapter mIndicaorAdapter;
    private RoundRectImageView mRoundRectImageView;
    private TextView mHeaderTitleTv;
    private TextView mSubTitleTv;
    private ImageView mPlayControlIv;
    private PlayerPresenter mPlayerPresenter;
    private String mCurrentTitle = null;
    private String mCurrentNickname = null;
    private String mCurrentCoverUrl = null;
    private View mPlayControl;
    private SmartRefreshLayout mSmartRefreshLayout;
    private View mSearchBtn;

    /* View是绘制在屏幕上的用户能与之交互的一个对象。
   而ViewGroup则是一个用于存放其他View（和ViewGroup）对象的布局容器*/
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        iniEvent();
        // 注册present
        initPresenter();
    }

    /*
    * 注册回调
    * */
    private void initPresenter() {
        mPlayerPresenter = PlayerPresenter.getInstance();
        mPlayerPresenter.registerViewCallback(this);

    }

    private void iniEvent() {
        mIndicaorAdapter.setOnIndicatorTapClickListener(new IndicaorAdapter.OnIndicatorTapClickListener() {
            @Override
            public void onTabClick(int index) {
                Log.d(TAG,"click index is :"+index);
                if (mContentPage != null) {
                    mContentPage.setCurrentItem(index);
                }

            }

        });
        mPlayControlIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mPlayerPresenter != null) {
                    boolean hasPlayList = mPlayerPresenter.hasPlayList();
                    if (hasPlayList) {
                        if (mPlayerPresenter.isPlay()) {
                            mPlayerPresenter.pause();
                        } else {
                            mPlayerPresenter.play();
                                }

                    } else {
                        // 没有设置播放的话，我们就播放默认的第一个专辑推荐
                        playFirstRecommend();
                    }
                }
            }
        });

        mPlayControl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                boolean hasPlayList = mPlayerPresenter.hasPlayList();
                if (hasPlayList) {

                } else {
                    playFirstRecommend();
                }
                startActivity(new Intent(MainActivity.this,PlayerActivity.class));
                // 跳转到播放器界面
            }
        });
        mSearchBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent= new Intent(MainActivity.this,SearchActivity.class);
                startActivity(intent);
            }
        });
    }

    private void playFirstRecommend() {
        List<Album> currentRecommend =  RecommendPresenter.getInstance().getCurrentRecommend();
        if (currentRecommend != null && currentRecommend.size()>0) {
            Album album = currentRecommend.get(0);
            long albumId = album.getId();
            mPlayerPresenter.playByAlbumId(albumId);
        }
    }

    private void initView() {
        mMagicIndicator = this.findViewById(R.id.main_indicator);   // 头栏
        mMagicIndicator.setBackgroundColor(this.getResources().getColor(R.color.main_color));  // 设置背景颜色；
        mIndicaorAdapter = new IndicaorAdapter(this);  // 创建适配器
        CommonNavigator commonNavigator = new CommonNavigator(this);  // 导航栏
        commonNavigator.setAdapter(mIndicaorAdapter);
        commonNavigator.setAdjustMode(true);  //  允许导航栏自我调节 会让导航栏 居中平分
        // 设置要显示的内容 TODO
        //adapter.se

        // ViewPager
        mContentPage = this.findViewById(R.id.content_page);
        // 创建内容适配器
        FragmentManager  supportFragmentManager = getSupportFragmentManager();
        MainContentAdapter mainContentAdapter = new MainContentAdapter(supportFragmentManager);  // MainContentAdapter继承自FragmentAdapter
        mContentPage.setAdapter(mainContentAdapter);



        mMagicIndicator.setNavigator(commonNavigator);  // 给头栏添加导航栏

        ViewPagerHelper.bind(mMagicIndicator, mContentPage);    //// 把ViewPager 和 indicator绑定到一起 给contentPage设置监听，当滑动的时候 或者
                                                                //停下的时候做出反应

        // 播放控制相关的
        mRoundRectImageView = this.findViewById(R.id.maintrack_cover);
        mHeaderTitleTv = this.findViewById(R.id.main_head_title);
        mHeaderTitleTv.setSelected(true);  // 设置焦点 ，解决不能滚动的问题
        mSubTitleTv = this.findViewById(R.id.main_sub_title);
        mPlayControlIv = this.findViewById(R.id.main_play_control);
        mPlayControl = this.findViewById(R.id.main_play_control_item);
        mSmartRefreshLayout = this.findViewById(R.id.over_scroll);
        //　搜索相关
        mSearchBtn = this.findViewById(R.id.main_search_btn);


    }

    private void updatePlayControl(boolean isPlay) {
        if (mPlayControlIv != null) {
            mPlayControlIv.setImageResource(isPlay?R.drawable.selector_palyer_pause:R.drawable.selector_palyer_play);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mPlayerPresenter.unRegisterViewCallback(this);
    }

    @Override
    public void onPLayStart() {
        updatePlayControl(true);
    }

    @Override
    public void onPlayPause() {
        updatePlayControl(false);
    }

    @Override
    public void onPlayStop() {
        updatePlayControl(false);
    }

    @Override
    public void onPlayError() {

    }

    @Override
    public void onNextPlay(Track track) {

    }

    @Override
    public void onPrePlay(Track track) {

    }

    @Override
    public void onListLoaded(List<Track> tracks) {

    }

    @Override
    public void onPlayModelChange(XmPlayListControl.PlayMode mode) {

    }

    @Override
    public void onProgressChange(long current, long title) {

    }

    @Override
    public void onADLoading() {

    }

    @Override
    public void onAdFinish() {

    }

    @Override
    public void onTrackUpdate(Track track, int position) {
        if (track != null) {
            mCurrentTitle = track.getTrackTitle();
            mCurrentNickname = track.getAnnouncer().getNickname();
            mCurrentCoverUrl = track.getCoverUrlMiddle();
            LogUtil.d(TAG,mCurrentTitle);
            LogUtil.d(TAG,mCurrentNickname);
            LogUtil.d(TAG,mCurrentCoverUrl);
            if (mHeaderTitleTv != null) {
                mHeaderTitleTv.setText(mCurrentTitle);
            }
            if (mSubTitleTv != null) {
                mSubTitleTv.setText(mCurrentNickname);
            }
            Picasso.with(this).load(mCurrentCoverUrl).into(mRoundRectImageView);
        }
    }
}